//
//  OrderSearchView.swift
//  swiftProject
//
//  Created by ZhangSai on 2021/6/15.
//

import UIKit



class OrderSearchView: UITextField,UITextFieldDelegate {
    typealias OrderSearchViewBlock = (_ type:TextFieldType) -> Void
    var orderSearchViewBlock : OrderSearchViewBlock!

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.delegate = self
        self.placeholder = ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.order_search_order)
        self.font = UIFont.systemFont(ofSize: 14)
        self.keyboardType = UIKeyboardType.default
        self.borderStyle = .none
        self.backgroundColor = UIColor.init(hexString: "#F2F2F1")
        self.layer.masksToBounds = true
        self.layer.cornerRadius = frame.size.height/2
        self.returnKeyType = UIReturnKeyType.search
        self.clearButtonMode = .always
                
        let searchImageView:UIImageView = UIImageView.init(frame: CGRect.init(x: 10, y: 0, width: 20, height: 15))
        searchImageView.center = CGPoint.init(x: 15, y: Constants.OrderHeaderSearchViewHeight / 2)
        searchImageView.image = UIImage.init(named: "address_search")
        searchImageView.contentMode = .scaleAspectFit
        self.addSubview(searchImageView)
        self.leftView = searchImageView
        self.leftViewMode = .unlessEditing
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if (orderSearchViewBlock != nil) {
            orderSearchViewBlock(TextFieldType.beginSearchType)
        }
        self.resignFirstResponder()
        return true
    }
    
    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        if (orderSearchViewBlock != nil) {
            orderSearchViewBlock(TextFieldType.clearType)
        }
        self.resignFirstResponder()
        return true
    }
    
    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        var tempBounds = bounds
        
        let oldRect = super.editingRect(forBounds: bounds)
        let x = oldRect.maxX
        let y = oldRect.maxY
        var width = oldRect.width
        width -= 30
        tempBounds.origin.x = x
        tempBounds.origin.y = y + 1
        tempBounds.size.width = width
        return tempBounds
    }
}
